package com.ms.service.impl;

import com.ms.mapper.AttendanceRecordMapper;
import com.ms.pojo.AttendanceRecord;
import com.ms.service.AttendanceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class AttendanceRecordServiceImpl implements AttendanceRecordService {
    @Autowired
    private AttendanceRecordMapper attendanceRecordMapper;

    //考勤时间配置
    private static final LocalTime NORMAL_CHECK_IN_TIME = LocalTime.of(9, 0);  // 正常签到时间 09:00
    private static final LocalTime NORMAL_CHECK_OUT_TIME = LocalTime.of(18, 0); // 正常签退时间 18:00


    @Override
    public void initDailyAttendance() {
        LocalDate today = LocalDate.now();
        // 查询所有在职员工ID
        attendanceRecordMapper.selectAllActiveEmpIds().forEach(empId -> {
            // 检查是否已存在当天记录（避免重复创建）
            AttendanceRecord existing = attendanceRecordMapper.selectByEmpAndDate(empId, today);
            if (existing == null) {
                AttendanceRecord record = new AttendanceRecord();
                record.setEmpId(empId);
                record.setAttendanceDate(today);
                record.setAttendanceStatus(3); // 初始状态：未签到
                record.setCreateTime(LocalDateTime.now());
                record.setUpdateTime(LocalDateTime.now());
                attendanceRecordMapper.insert(record);
            }
        });
    }

    @Override
    public AttendanceRecord checkIn(Integer empId) {
        if (empId == null) {
            return null;
        }

        LocalDate today = LocalDate.now();
        AttendanceRecord record = attendanceRecordMapper.selectByEmpAndDate(empId, today);
        if (record == null) {
            // 极端情况：定时任务未执行，手动创建当天记录
            record = new AttendanceRecord();
            record.setEmpId(empId);
            record.setAttendanceDate(today);
            record.setAttendanceStatus(3); // 未签到
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            attendanceRecordMapper.insert(record);
        }

        // 已签到判断
        if (record.getCheckInTime() != null) {
            return null;
        }

        // 执行签到
        LocalDateTime now = LocalDateTime.now();
        record.setCheckInTime(now);
        // 判断是否迟到（9:00后签到）
        record.setAttendanceStatus((int) (now.toLocalTime().isAfter(NORMAL_CHECK_IN_TIME) ? (byte) 1 : (byte) 0));
        record.setUpdateTime(now);
        attendanceRecordMapper.updateCheckIn(record);

        return record;
    }

    @Override
    public AttendanceRecord checkOut(Integer empId) {
        if (empId == null) {
            return null;
        }

        LocalDate today = LocalDate.now();
        AttendanceRecord record = attendanceRecordMapper.selectByEmpAndDate(empId, today);
        // 未找到记录或未签到
        if (record == null || record.getCheckInTime() == null) {
            return null;
        }
        // 已签退判断
        if (record.getCheckOutTime() != null) {
            return null;
        }

        // 执行签退
        LocalDateTime now = LocalDateTime.now();
        record.setCheckOutTime(now);
        // 判断是否早退（18:00前签退）
        LocalTime checkOutTime = now.toLocalTime();
        if (checkOutTime.isBefore(NORMAL_CHECK_OUT_TIME)) {
            record.setAttendanceStatus(2); // 早退
            // 计算早退分钟数
            long minutes = ChronoUnit.MINUTES.between(checkOutTime, NORMAL_CHECK_OUT_TIME);
            record.setEarlyMinutes((int) minutes);
        }
        record.setUpdateTime(now);
        attendanceRecordMapper.updateCheckOut(record);

        return record;
    }

    @Override
    public AttendanceRecord getTodayAttendance(Integer empId) {
        return attendanceRecordMapper.selectByEmpAndDate(empId, LocalDate.now());
    }
    @Override
    public List<AttendanceRecord> getAllRecords() {
        return attendanceRecordMapper.selectAllRecords();
    }
}
